// packageA/pages/opinion/opinion.js
import global from '../../utils/global'
import {
    insertBankCardNo
} from '../../api/app.js'
import user from '../../utils/user'
import bankList from '../../utils/bankList.js';
const app = getApp()
Page({
    onLoad(options) {
        console.log(user, 'options.isCollectBankCardImgoptions.isCollectBankCardImgoptions.isCollectBankCardImg');
        this.setData({
            isCollectOpenBankAddressflag: options.isshowCollectOpenBankAddress === '1' ? true : false,
            isCollectOpenBankName: !(options.isCollectOpenBankName === '0'),
            isCollectOpenBankCity: !(options.isCollectOpenBankCity === '0'),
            isCollectBankCardImg: !(options.isCollectBankCardImg === '0'),
            // id来自于领薪，从个人信息来的没有id，保存的时候判断返回到对应的页面
            id: options.id || '',
            bankCard: user.bankCardNo ? user.bankCardNo.replace(/\s/g, '').replace(/....(?!$)/g, '$& ') : '',
            'formData.bankCard': user.bankCardNo ? user.bankCardNo.replace(/\s/g, '').replace(/....(?!$)/g, '$& ') : '',
            'formData.openBank': user.openBankName || '',
            'formData.bankCardurl': user.bankCardImg ? user.bankCardImg : user.bankCardImg || '',
            'dataInformation.bankcardurl': user.bankCardImg ? user.bankCardImg : user.bankCardImg || '',
            'formData.branchBank': user.openBankBranch || '',
            'formData.name': user.userName ? user.userName : user.userName || '',
            'formData.region': user.openBankCity?.length ? user.openBankCity.split(',') : [],
            from: user.from || '',
        })

        if (options.isCollectOpenBankName === '1') {
            this.data.rules.push({
                    name: "openBank",
                    rules: [{
                        required: true,
                        message: '请选择开户银行'
                    }]
                },
                // {
                //     name: "branchBank",
                //     rules: [
                //         {
                //             required: true,
                //             message: '请输入开户行支行'
                //         }
                //     ]
                // }
            )
        }

        if (options.isCollectOpenBankCity === '1') {
            this.data.rules.push({
                name: "region",
                rules: [{
                    validator: function (rule, value, param, modeels) {
                        if (!value?.length) {
                            return '请选择开户城市'
                        }
                    }
                }]
            })
        }

        this.setData({
            rules: this.data.rules
        })

        console.log(4444, this.data.rules);
        console.log(this.data.bankCard, 'bankCard')
        console.log(options, 'options')
        console.log(user, 'user')
    },
    /**
     * 页面的初始数据
     */
    data: {
        from: '', // 来自于领薪还是预支
        bankCard: '',
        id: '',
        bankCardaddress: "",
        isCollectOpenBankAddressflag: false,
        isCollectOpenBankName: true,
        isCollectOpenBankCity: true,
        isCollectBankCardImg: true,
        error: '',
        formData: {
            name: '',
            bankCard: '',
            openBank: '',
            branchBank: '',
            region: [],
            regionId: [],
            bankIndex: '',
            bankCardurl: '',
        },
        rules: [{
                name: 'bankCard',
                rules: [{
                        required: true,
                        message: '请输入银行卡号'
                    },
                    {
                        validator: function (rule, value, param, modeels) {
                            let bank_reg = /^[1-9]\d{9,29}$/
                            if (value.replace(/\s*/g, "").length < 16 || value.replace(/\s*/g, "").length > 19) {
                                return '银行卡号码不得低于16位，不得高于19位'
                            }
                            if (bank_reg.test(value.replace(/\s*/g, "")) === false) {
                                return '请输入正确的银行卡号'
                            }
                        }
                    }
                ]
            },
            // {
            //     name: "openBank",
            //     rules: [
            //         {
            //             required: false,
            //             message: '请选择开户银行'
            //         }
            //     ]
            // },
            // {
            //     name: "branchBank",
            //     rules: [
            //         {
            //             required: false,
            //             message: '请输入开户行支行'
            //         }
            //     ]
            // },
            // {
            //     name: "region",
            //     rules: [
            //         {
            //             validator: function (rule, value, param, modeels) {
            //                 if (!value?.length) {
            //                     return '请选择开户城市'
            //                 }
            //             }
            //         }
            //     ]
            // },
        ],
        curBank: {},
        bankArray: bankList,
        showBankList: false,
        searchBankName: ''
    },
    async onBankCard() {
        wx.navigateTo({
            url: '/pages/demo/demo?type=' + '3',
            events: {
                BankCard: async (base64) => {
                    console.log(base64);
                    this.setData({
                        ['dataInformation.bankcardurl']: base64.url
                    })
                    wx.uploadFile({
                        url: global.baseUrl + '/api/v1/blue/user/upload',
                        filePath: base64.url,
                        name: 'file',
                        formData: {
                            'user': 'test'
                        },
                        success: (res) => {
                            const data = res.data
                            console.log(JSON.parse(data).data.fileUrl);
                            this.setData({
                                ['formData.bankCardurl']: JSON.parse(data).data.fileUrl
                            })
                        }
                    })
                }
            }
        })
    },
    onDeleteCard(ev) {
        this.setData({
            'formData.bankCard': ''
        })
    },
    onDeleteBranchCard(ev) {
        this.setData({
            'formData.branchBank': ''
        })
    },
    inputchange(event) {
        console.log(event, 'eventevent')
        const {
            value
        } = event.detail
        this.setData({
            bankCard: value.replace(/\s/g, '').replace(/....(?!$)/g, '$& ')
        })
    },
    inputchangeaddress(event) {
        console.log(event, 'eventevent')
        const {
            value
        } = event.detail
        this.setData({
            bankCardaddress: value
        })
    },
    async onInsertBankCardNo() {
        this.selectComponent('#form').validate(async (valid, errors) => {
            if (!valid) {
                const firstError = Object.keys(errors)
                if (firstError.length) {
                    app.toast(errors[firstError[0]].message)
                }
            } else {
                await insertBankCardNo({
                    userName: this.data.formData.name,
                    bankCardNo: this.data.formData.bankCard.replace(/\s*/g, "") || null,
                    openBankAddress: this.data.formData.openBank || null,
                    openBankName: this.data.formData.openBank || null,
                    openBankBranch: this.data.formData.branchBank || null,
                    openBankCity: this.data.formData.region?.length ? this.data.formData.region.join(',') : null,
                    bankCardImg: this.data.formData.bankCardurl,
                })
                await app.toast('创建成功')
                await user.reLogin()
                // 有
                if (this.data.from === 'salary') {
                    wx.redirectTo({
                        url: '/pages/salary-list-details/salary-list-details?id=' + this.data.id
                    })
                } else if (this.data.from === 'advance') {
                    wx.redirectTo({
                        url: '/pages/advance-details/advance-details?id=' + this.data.id
                    })
                } else {
                    wx.navigateBack()
                }
            }
        })
        return
        let bank_reg = /^[1-9]\d{9,29}$/
        if (!this.data.bankCard.replace(/\s*/g, "")) {
            await app.toast('请输入银行卡号码')
            return
        }
        if (this.data.bankCard.replace(/\s*/g, "").length < 16 || this.data.bankCard.replace(/\s*/g, "").length > 19) {
            await app.toast('银行卡号码不得低于16位，不得高于19位')
            return
        }
        console.log(this.data.bankCard.replace(/\s*/g, ""), '银行卡')
        if (bank_reg.test(this.data.bankCard.replace(/\s*/g, "")) === false) {
            await app.toast('请输入正确的银行卡号')
            return
        }
        await app.confirm('确定保存当前银行卡号！')
        await insertBankCardNo({
            bankCardNo: this.data.bankCard.replace(/\s*/g, ""),
            openBankAddress: this.data.bankCardaddress === '' ? null : this.data.bankCardaddress,
        })
        await app.toast('创建成功')
        wx.redirectTo({
            url: '/pages/salary-list-details/salary-list-details?id=' + this.data.id
        })
        console.log(result, 'result')
    },
    async onEditInsertBankCardNo() {
        this.selectComponent('#form').validate(async (valid, errors) => {
            if (!valid) {
                const firstError = Object.keys(errors)
                if (firstError.length) {
                    app.toast(errors[firstError[0]].message)
                }
            } else {
                await insertBankCardNo({
                    userName: this.data.formData.name,
                    bankCardNo: this.data.formData.bankCard.replace(/\s*/g, "") || null,
                    openBankAddress: this.data.formData.openBank || null,
                    openBankName: this.data.formData.openBank || null,
                    openBankBranch: this.data.formData.branchBank || null,
                    openBankCity: this.data.formData.region?.length ? this.data.formData.region.join(',') : null,
                    bankCardImg: this.data.formData.bankCardurl,
                })
                await app.toast('修改成功')
                await user.reLogin()
                user.bankCardNo = this.data.bankCard.replace(/\s*/g, "")
                setTimeout(() => {
                    wx.navigateBack()
                }, 1000)
            }
        })
        return
        let bank_reg = /^[1-9]\d{9,29}$/
        if (!this.data.bankCard.replace(/\s*/g, "")) {
            await app.toast('请输入银行卡号码')
            return
        }
        if (this.data.bankCard.replace(/\s*/g, "").length < 16 || this.data.bankCard.replace(/\s*/g, "").length > 19) {
            await app.toast('银行卡号码不得低于16位，不得高于19位')
            return
        }
        console.log(this.data.bankCard.replace(/\s*/g, ""), '银行卡')
        if (bank_reg.test(this.data.bankCard.replace(/\s*/g, "")) === false) {
            await app.toast('请输入正确的银行卡号')
            return
        }
        if (this.data.isCollectOpenBankAddressflag && this.data.bankCardaddress === '') {
            await app.toast('请输入银行卡开户行地址！')
            return
        }
        await app.confirm('确定修改银行卡！')
        await insertBankCardNo({
            bankCardNo: this.data.bankCard.replace(/\s*/g, ""),
            openBankAddress: this.data.bankCardaddress === '' ? null : this.data.bankCardaddress,
        })
        await app.toast('修改成功')
        user.bankCardNo = this.data.bankCard.replace(/\s*/g, "")
        setTimeout(() => {
            wx.navigateBack()
        }, 1000)
    },
    handleFocus(ev) {
        this.setData({
            showBankList: true
        })
    },
    handleOpenBank(ev) {
        wx.navigateTo({
            url: '/pages/bank-list/bank-list',
            events: {
                bankName: (data) => {
                    if (data?.name) {
                        this.setData({
                            'formData.openBank': data.name
                        })
                    }
                }
            },
            // success(res) {
            //   res.eventChannel.on('selectBank', (data) => {
            //     console.log(1111, data);
            //   })
            // }
        })
    },
    handleBankCardInput(ev) {
        this.setData({
            'formData.bankCard': ev.detail.value
        })
    },
    handleBranchBankInput(ev) {
        this.setData({
            'formData.branchBank': ev.detail.value
        })
    },
    bindBankChange(ev) {
        this.setData({
            'formData.bankIndex': ev.detail.value,
            'formData.openBank': this.data.bankArray[ev.detail.value].name,
            curBank: this.data.bankArray[ev.detail.value]
        })
    },
    bindRegionChange(ev) {
        this.setData({
            'formData.region': ev.detail.value,
            'formData.regionId': ev.detail.code
        })
    },
    handleSelect(ev) {
        const value = ev.target.dataset
        this.setData({
            'formData.openBank': value.name,
            showBankList: false
        })
    },
    handleSearch(ev) {
        const value = ev.detail.value
        let list = bankList
        if (value) {
            list = bankList.filter(i => i.name.includes(value))
        }
        this.setData({
            bankArray: list,
            searchBankName: value
        })
    },
    setBankName(ev) {
        this.setData({
            'formData.openBank': this.data.searchBankName,
            showBankList: false
        })
    },
    handleInit() {
        this.setData({
            searchBankName: '',
            bankArray: bankList
        })
    }
})